import logging
import os
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask_cors import CORS
from flask_migrate import Migrate
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy

from config import app_config

app = Flask(__name__)
db = SQLAlchemy()
migrate = Migrate(app, db)
moment = Moment()


def create_app(config):
    # cors
    CORS(app, resources={r"/api/v1.0/*": {"origins": "*"}})

    config_name = config
    if not isinstance(config, str):
        config_name = os.getenv('FLASK_CONFIG', 'default')
    app_config[config_name].init_app(app)
    app.config.from_object(app_config[config_name])

    db.init_app(app)
    moment.init_app(app)

    from .errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from .api import bp as api_bp
    app.register_blueprint(api_bp, url_prefix='/api/v1.0')

    if app.config['LOG_TO_STDOUT']:
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(logging.INFO)
        app.logger.addHandler(stream_handler)

    if not app.debug and not app.testing:
        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler('logs/face-recognition.log', maxBytes=10240, backupCount=10)
        formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
        file_handler.setFormatter(formatter)
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('Face Recognition App startup')

    return app
